package leetcode.hot100;

import leetcode.tester.ArgsEnum;
import leetcode.tester.Tester;

import java.util.*;

/**
 * 49. 字母异位词分组
 * https://leetcode.cn/problems/group-anagrams/description/?envType=study-plan-v2&envId=top-100-liked
 *
 * @author Liu Yicong
 * @date 2025/9/28
 */
public class Hot2HashGroupAnagrams {
	public static void main(String[] args) {
		Object[][] inputs = {
				new Object[]{new String[]{"eat", "tea", "tan", "ate", "nat", "bat"},},
				new Object[]{new String[]{"a"},},
				new Object[]{new String[]{""},}};
		Object[] outputs = {
				new Object[]{new String[]{"bat"}, new String[]{"nat", "tan"}, new String[]{"ate", "eat", "tea"}},
				new Object[]{new String[]{"a"}},
				new Object[]{new String[]{""}}};
		Tester.test(Tester.wrap(new Hot2HashGroupAnagrams()::groupAnagrams), inputs, outputs, new ArgsEnum[]{ArgsEnum.IGNORE_ORDER});
	}

	public List<List<String>> groupAnagrams(String[] strs) {
		Map<String, List<String>> map = new HashMap<>();
		for (String str : strs) {
			char[] cs = str.toCharArray();
			Arrays.sort(cs);
			String sorted = String.valueOf(cs);
			if (map.get(sorted) != null) {
				map.get(sorted).add(str);
			}else {
				List<String> list = new ArrayList<>();
				list.add(str);
				map.put(sorted,list);
			}
		}
		List<List<String>> ans = new ArrayList<>();
		for (String key: map.keySet()){
			ans.add(map.get(key));
		}
		return ans;
	}

}
